package org.example.batchutils.datasource;

import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.example.batchutils.mapper.DataSourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
public class DataSourceConfigService {

    @Autowired
    private DataSourceConfigRepository configRepository;

    @Autowired
    private DataSourceBuilderService dataSourceBuilder;

    /**
     * 从数据库加载所有数据源配置
     */
    public Map<String, DataSource> loadAllDataSources() {
        List<DataSourceConfig> configs = configRepository.findAll();
        Map<String, DataSource> dataSourceMap = new HashMap<>();

        for (DataSourceConfig config : configs) {
            DataSource dataSource = dataSourceBuilder.buildDataSource(config);
            log.info("加载数据源：{}", config.getPollName());
            dataSourceMap.put(config.getPollName(), dataSource);
        }

        return dataSourceMap;
    }

    /**
     * 根据key获取单个数据源配置
     */
    public Optional<DataSource> getDataSourceByKey(String pollName) {
        return configRepository.findByPollName(pollName)
                .map(dataSourceBuilder::buildDataSource);
    }

    /**
     * 添加新的数据源配置
     */
    @Transactional
    public DataSourceConfig saveDataSourceConfig(DataSourceConfig config) {
        return configRepository.save(config);
    }

    /**
     * 更新数据源配置
     */
    @Transactional
    public DataSourceConfig updateDataSourceConfig(Long id, DataSourceConfig config) {
        config.setId(id);
        return configRepository.save(config);
    }

    /**
     * 删除数据源配置
     */
    @Transactional
    public void deleteDataSourceConfig(Long id) {
        configRepository.deleteById(id);
    }
}
